﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreData;
using EntityData;
using Helper;
using Services.BusinessRules;
using System.Data;
namespace Services
{

    public partial class ClassService
    {
       readonly IClassEntity entity;
       readonly IAuditEntity AuditEntity;
       readonly IClass_FeeTimeEntity ClassFeeTimeEntity;
       public ClassService()
       {
           this.entity = new ClassEntity();
           this.AuditEntity = new AuditEntity();
           this.ClassFeeTimeEntity = new Class_FeeTimeEntity();
       }


       #region SQL
       const string codeclass = " select top 1 Code from Class where {0} order by ID DESC";
       #endregion

       #region Main Method

       /// <summary>
       /// Save 
       /// </summary>
       /// <param name="_model"></param>
       /// <returns></returns>
       public long Save(object _model,ref string mess)
       {
           try
           {
               Audit audit = new Audit();
               audit.ModifiedDate = DateTime.Now;
               audit.UserID = ValueDefine.UserID;
               audit.Module = "Lớp học";
               audit.Code = "Class";
               var obj = (Class)_model;
               if (Validate(obj, ref mess))
               {
                   var id = long.Parse(_model.GetType().GetProperty("ID").GetValue(_model, null).ToString());
                   if (id == 0)
                   {
                       audit.Action = "Thêm mới";
                       audit.Description = Diff(new Class(), (Class)_model);
                       AuditEntity.Save(audit, Table.Audit.ToString());
                       var classid = entity.Save((CoreData.Class)_model, Table.Class.ToString());

                       //dong 1 lan
                       Class_FeeTime f1 = new Class_FeeTime();
                       f1.ClassID = classid ;
                       f1.Times = "Một lần";
                       f1.Type = 1;

                       // nếu là một lần thì láy ngày bắt đầu khóa học -1 tháng
                       // ví dụ khóa khai giảng thang 8 thì start là tháng 7 và end là tháng 8

                       f1.StartDate1 = obj.StartDate.AddMonths(-1);
                       f1.EndDate1 = obj.StartDate;
                       f1.Money1 = obj.Price + ValueDefine.dongmotlan;
                       ClassFeeTimeEntity.Save(f1, Table.Class_FeeTime.ToString());

                       //dong 2 lan
                       Class_FeeTime f2 = new Class_FeeTime();
                       f2.ClassID = classid;
                       f2.Type = 2;
                       f2.Times = "Hai lần";
                       // nếu là 2 lần thì lan 1 láy ngày bắt đầu khóa học -3 tháng
                       //lan 2 thu ngay khai giang den bat dat cua lan 2
                       // ví dụ khóa khai giảng thang 8 thì start là tháng 7 và end là tháng 8

                       //f2.StartDate1 = obj.StartDate;
                       //f2.EndDate1 = f2.StartDate1.AddMonths(3);

                       //f2.StartDate2 = f2.EndDate1;
                       //f2.EndDate2 = obj.EndDate;

                       f2.StartDate1 = obj.StartDate.AddMonths(-3);
                       f2.EndDate1 = obj.StartDate;

                       f2.StartDate2 = f2.EndDate1;
                       f2.EndDate2 = obj.StartDate.AddMonths(3);

                       f2.Money1 = (obj.Price + ValueDefine.donghailan) / 2;
                       f2.Money2 = (obj.Price + ValueDefine.donghailan) / 2;
                       ClassFeeTimeEntity.Save(f2, Table.Class_FeeTime.ToString());

                       if (obj.Type != 0)//neu la khoa ngan han thi chi tao 2 lan
                       {
                           ////dong 3 lan (bỏ đi)
                           //Course_FeeTime f3 = new Course_FeeTime();
                           //f3.CourseID = course_id;
                           //f3.Type = 3;
                           //f3.Times = "Ba lần";
                           //f3.StartDate1 = obj.StartDate;
                           //f3.EndDate1 = f3.StartDate1.AddMonths(2);

                           //f3.StartDate2 = f3.EndDate1;
                           //f3.EndDate2 = f3.StartDate2.AddMonths(2);

                           //f3.StartDate3 = f3.EndDate2;
                           //f3.EndDate3 = obj.EndDate;

                           //f3.Money1 = obj.Price / 3;
                           //f3.Money2 = obj.Price / 3;
                           //f3.Money3 = obj.Price / 3;
                           //course_feeentity.Save(f3, Table.Course_FeeTime.ToString());


                           //dong 4 lan
                           Class_FeeTime f4 = new Class_FeeTime();
                           f4.ClassID = classid;
                           f4.Type = 4;
                           f4.Times = "Bốn lần";


                           //f4.StartDate1 = obj.StartDate;
                           //f4.EndDate1 = f4.StartDate1.AddMonths(1).AddDays(15);

                           //f4.StartDate2 = f4.EndDate1;
                           //f4.EndDate2 = f4.StartDate2.AddMonths(1).AddDays(15);


                           //f4.StartDate3 = f4.EndDate2;
                           //f4.EndDate3 = f4.StartDate3.AddMonths(1).AddDays(15);

                           //f4.StartDate4 = f4.EndDate3;
                           //f4.EndDate4 = obj.EndDate;


                           f4.StartDate1 = obj.StartDate.AddMonths(-1).AddDays(-15);
                           f4.EndDate1 = obj.StartDate;

                           f4.StartDate2 = f4.EndDate1;
                           f4.EndDate2 = f4.StartDate2.AddMonths(1).AddDays(15);

                           f4.StartDate3 = f4.EndDate2;
                           f4.EndDate3 = f4.StartDate3.AddMonths(1).AddDays(15);

                           f4.StartDate4 = f4.EndDate3;
                           f4.EndDate4 = f4.StartDate4.AddMonths(1).AddDays(15);

                           f4.Money1 = (obj.Price + ValueDefine.dongbonlan) / 4;
                           f4.Money2 = (obj.Price + ValueDefine.dongbonlan) / 4;
                           f4.Money3 = (obj.Price + ValueDefine.dongbonlan) / 4;
                           f4.Money4 = (obj.Price + ValueDefine.dongbonlan) / 4;
                           ClassFeeTimeEntity.Save(f4, Table.Class_FeeTime.ToString());


                           //dong 6 lan
                           Class_FeeTime f6 = new Class_FeeTime();
                           f6.ClassID = classid;
                           f6.Type = 6;
                           //f6.StartDate1 = obj.StartDate;
                           //f6.EndDate1 = f6.StartDate1.AddMonths(1);
                           f6.Times = "Sáu lần";
                           //f6.StartDate2 = f6.EndDate1;
                           //f6.EndDate2 = f6.StartDate2.AddMonths(1);

                           //f6.StartDate3 = f6.EndDate2;
                           //f6.EndDate3 = f6.StartDate3.AddMonths(1);

                           //f6.StartDate4 = f6.EndDate3;
                           //f6.EndDate4 = f6.StartDate4.AddMonths(1);

                           //f6.StartDate5 = f6.EndDate4;
                           //f6.EndDate5 = f6.StartDate5.AddMonths(1);

                           //f6.StartDate6 = f6.EndDate5;
                           //f6.EndDate6 = obj.EndDate;

                           f6.StartDate1 = obj.StartDate.AddMonths(-1);
                           f6.EndDate1 = obj.StartDate;

                           f6.StartDate2 = f6.EndDate1;
                           f6.EndDate2 = f6.StartDate2.AddMonths(1);

                           f6.StartDate3 = f6.EndDate2;
                           f6.EndDate3 = f6.StartDate3.AddMonths(1);

                           f6.StartDate4 = f6.EndDate3;
                           f6.EndDate4 = f6.StartDate4.AddMonths(1);

                           f6.StartDate5 = f6.EndDate4;
                           f6.EndDate5 = f6.StartDate5.AddMonths(1);

                           f6.StartDate6 = f6.EndDate5;
                           f6.EndDate6 = f6.StartDate6.AddMonths(1);

                           f6.Money1 = (obj.Price + ValueDefine.dongsaulan) / 6;
                           f6.Money2 = (obj.Price + ValueDefine.dongsaulan) / 6;
                           f6.Money3 = (obj.Price + ValueDefine.dongsaulan) / 6;
                           f6.Money4 = (obj.Price + ValueDefine.dongsaulan) / 6;
                           f6.Money5 = (obj.Price + ValueDefine.dongsaulan) / 6;
                           f6.Money6 = (obj.Price + ValueDefine.dongsaulan) / 6;
                           ClassFeeTimeEntity.Save(f6, Table.Class_FeeTime.ToString());
                       }
                       return classid;

                   }
                   else
                   {
                       audit.Action = "Cập nhật";
                       audit.Description = Diff(GetByID(id), (Class)_model);
                       AuditEntity.Save(audit, Table.Audit.ToString());
                       return entity.Update((CoreData.Class)_model, Table.Class.ToString());
                   }
               }
               else {
                   return -1;
               }
           }
           catch { return -1; }
       }

       /// <summary>
       /// Get by ID
       /// </summary>
       /// <param name="_id"></param>
       /// <returns></returns>
       public CoreData.Class GetByID(long _id)
       {
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetAllClass, " Class.ID="+_id)).ToList()[0];
               //return entity.GetById(_id, Table.Class.ToString());
           }
           catch { return null; }
       }

       /// <summary>
       /// Get List
       /// </summary>
       /// <returns></returns>
       public IList<CoreData.Class> GetList()
       {
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetAllClass," Class.IsDeleted = 'false' ")).ToList();
           }
           catch { return null; }

       }

       /// <summary>
       /// Get List with Linq
       /// </summary>
       /// <returns></returns>
       public IList<CoreData.Class> GetListByLINQ(Func<CoreData.Class, Boolean> _where)
       {
           try
           {
               return entity.GetMany(_where, Table.Class.ToString()).ToList();
           }
           catch { return null; }
       }
       /// <summary>
       /// Get One with Linq
       /// </summary>
       /// <returns></returns>
       public CoreData.Class GetOneByLINQ(Func<CoreData.Class, Boolean> _where)
       {
           try
           {
               return entity.Get(_where, Table.Class.ToString());
           }
           catch { return null; }
       }

       /// <summary>
       /// Get List with search string
       /// </summary>
       /// <returns></returns>
       public IList<CoreData.Class> GetList(string _searchstring)
       {
           //search theo tieu chi nao do         
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetAllClass, "Class.IsDeleted = 'false'  and " + _searchstring )).ToList();
           }
           catch { return null; }
       }


       /// <summary>
       /// Delete
       /// </summary>
       /// <param name="_model"></param>
       /// <returns></returns>
       public bool Delete(object _model)
       {
           try
           {
               entity.Delete((CoreData.Class)_model, Table.Class.ToString());

               Audit audit = new Audit();
               audit.ModifiedDate = DateTime.Now;
               audit.UserID = ValueDefine.UserID;
               audit.Module = "Lớp học";
               audit.Code = "Class";
               audit.Action = "Xóa";
               audit.Description = " Xóa lớp: " + ((CoreData.Class)_model).Name;
               AuditEntity.Save(audit, Table.Audit.ToString());

               return true;
           }
           catch { return false; }
       }


       /// <summary>
       /// Delete a object by hidden
       /// </summary>
       /// <param name="_model"></param>
       /// <returns></returns>
       public bool UpdateIsDelete(object _model)
       {
           try
           {
               var obj = (CoreData.Class)_model;
               obj.IsDeleted = true;
               entity.Update(obj, Table.Class.ToString());


               Audit audit = new Audit();
               audit.ModifiedDate = DateTime.Now;
               audit.UserID = ValueDefine.UserID;
               audit.Module = "Lớp học";
               audit.Code = "Class";
               audit.Action = "Xóa";
               audit.Description = " Xóa lớp: " + obj.Name;
               AuditEntity.Save(audit, Table.Audit.ToString());

               return true;
           }
           catch { return false; }
       }


       #endregion



        #region Other Method




       public IList<CoreData.Class> GetByCourseID(long courseID)
       {
           return GetList(" Class.CourseID=" + courseID);
       }



       public IList<CoreData.Class> GetByTeacherID(long TeacherID)
       {
           return GetList(" Class.MainTeacherID=" + TeacherID);
       }

      

       bool Validate(Class obj, ref string mess)
       {

           new ValidateRequired("Mã lớp", "Code", obj.Code);
           new ValidateRequired("Tên lớp", "Name", obj.Name);
          // new ValidateExist("Mã lớp", "Code", "Code", obj, GetList().Cast<object>().ToList());
        //   new ValidateExist("Tên lớp", "Name", "Name", obj, GetList().Cast<object>().ToList());
           new ValidateID("Khóa học", "Course", obj.CourseID);
           new ValidateID("Ngành học", "Branch", obj.BranchID);
           new ValidateID("Giáo viên chủ nhiệm", "Teacher", obj.MainTeacherID);
           new ValidateRangeDateTime("Ngày", "", obj.StartDate, obj.EndDate);


           mess = BusinessObject.Validate();
           BusinessObject.Clear();

           if (mess == null)
           {

               var code = GetByCode(obj.Code);
               if (code != null && (obj.ID != code.ID))
               {
                   mess = "Mã lớp bị trùng";
               }
           }
           if (mess == null)
           {

               var code = GetByName(obj.Name);
               if (code != null && (obj.ID != code.ID))
               {
                   mess = "Tên lớp bị trùng";
               }
           }


           return mess == null ? true : false;
       }

       public CoreData.Class GetByCode(string Code)
       {
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetAllClass, " Class.Code='" + Code+"'")).ToList()[0];
               //return entity.GetById(_id, Table.Class.ToString());
           }
           catch { return null; }
       }
       public CoreData.Class GetByName(string Code)
       {
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetAllClass, " Class.Name='" + Code + "'")).ToList()[0];
               //return entity.GetById(_id, Table.Class.ToString());
           }
           catch { return null; }
       }
        public IList<Class> GetByBranchID(long BranchID)
       {
           try
           {
               return GetList(" Class.BranchID =" + BranchID).ToList() ;
           }
           catch { return null; }
        }

       string Diff(Class OldItem, Class NewItem)
       {
           string content = "";
           if (NewItem.ID == 0)
           {
               content = "Thêm mới một lớp học: " + NewItem.Name;
           }
           else
           {
               if (OldItem.Code != NewItem.Code)
               {
                   content += "1. Mã: " + OldItem.Code + " --> " + NewItem.Code + "\r\n";
               }
               if (OldItem.Name != NewItem.Name)
               {
                   content += "2. Tên: " + OldItem.Name + " --> " + NewItem.Name + "\r\n";
               }
               if (OldItem.MainTeacherID != NewItem.MainTeacherID)
               {
                   content += "3. ID Giáo Viên: " + OldItem.MainTeacherID + " --> " + NewItem.MainTeacherID + "\r\n";
               }
               if (OldItem.Size != NewItem.Size)
               {
                   content += "3. Sỉ số: " + OldItem.Size + " --> " + NewItem.Size + "\r\n";
               }
               if (OldItem.Study_Time != NewItem.Study_Time)
               {
                   content += "4. Giờ học: " + OldItem.Study_Time + " --> " + NewItem.Study_Time + "\r\n";
               }
               if (OldItem.Description != NewItem.Description)
               {
                   content += "5. Ghi chú: " + OldItem.Description + " --> " + NewItem.Description + "\r\n";
               }
               if (OldItem.Active != NewItem.Active)
               {
                   content += "6. Đã học xong: " + OldItem.Active + " --> " + NewItem.Active + "\r\n";
               }
           }
           return content;
       }


        public string GenCodeClass(string code)
       {
           try
           {
               string Autonum = "01";
               try
               {
                   string search = " Code like '" + code + "%'";
                   if(code.Length<=1)
                   {
                       search += " and Class.Type=1 ";
                    }
                   var data = entity.GetByCusTomSQL(String.Format(codeclass, search)).First();

                   if (!String.IsNullOrEmpty(code))
                   {
                       var tempcode = data.Code.Substring(code.Length);
                       int autonum = int.Parse(tempcode) + 1;
                       if (autonum <= 9)
                       {
                           Autonum = "0" + autonum.ToString();
                       }
                       else
                       {
                           Autonum = autonum.ToString();
                       }
                   }
               }
               catch { }
             
               code += Autonum;
               
               return code;

           }
           catch { return ""; }
        }


        /// <summary>
        /// Lấy báo cáo danh sách các lớp chưa tốt nghiệp
        /// </summary>
        /// <param name="SearchString"></param>
        /// <returns></returns>
        public DataTable  GetReportClassNotDone(string SearchString)
        {
            try
            {

                return entity.GetByCusTomSQLReturnDatatable(String.Format(SQLCommand.GetReportClass, SearchString));
            }
            catch { return new DataTable(); }
        }


        #endregion 
    
    }
         
}
